<template>
  <div class="mysearch">
    <div class="box">
      <el-input
        type="text"
        v-model="input"
        placeholder="请输入要搜索的城市"
        :prefix-icon="Search"
        @input="searchCityLists"
      >
        <template #suffix>
          <el-icon @click="closeClick" class="el-input__icon"
            ><close
          /></el-icon> </template
      ></el-input>
    </div>
    <div class="show-lists">
      <template v-for="item in cityList" :key="item">
        <div class="li" @click="cityClick(item)">{{ item.name }}</div>
      </template>
    </div>
  </div>
</template>

<script setup>
import { getIPValue } from "@/services/public/index";

import usePublicStore from "@/stores/modules/public";
import { storeToRefs } from "pinia";

// 防抖函数
import { debounce } from "@/utils/debounce";
// 图标
import { Search } from "@element-plus/icons-vue";

const publicStore = usePublicStore();
const { showSearch } = storeToRefs(publicStore);

const input = ref("");
const cityList = ref([]);
const searchName = ref("");

const closeClick = () => {
  cityList.value = [];
  input.value = "";
  showSearch.value = false;
};

// 输入框失去焦点时
const blurChange = () => {
  cityList.value = [];
};

const searchCity = () => {
  getIPValue(input.value).then((res) => {
    // console.log(res);
    if (res.data.code == 404) {
      cityList.value = [{ name: "找不到该城市" }];
    } else {
      let result = [];
      // 找到该城市
      if (input.value.indexOf("市") != -1) {
        searchName.value = input.value.replace("市", "");
      } else {
        searchName.value = input.value;
      }
      // 多个数据匹配
      for (let i in res.data.location) {
        if (res.data.location[i].name.indexOf(searchName.value) > -1) {
          result.push(res.data.location[i]);
        }
      }
      if (!result.length) {
        cityList.value = [];
      } else {
        cityList.value = result;
        searchName.value = "";
      }
    }
  });
};

// // 添加防抖
const searchCityLists = debounce(searchCity, 500);

// 城市搜索
const cityClick = (item) => {
  publicStore.city = item.name;
  publicStore.code = item.id;
  closeClick();
};
</script>

<style lang="less" scoped>
.mysearch {
  position: absolute;
  top: 0px;
  right: 0px;
  max-width: 1180px;
  z-index: 10;
  .box {
    height: 30px;
    // width: 100%;
  }
  .show-lists {
    position: absolute;
    top: 35px;
    width: 100%;
    padding: 0 5px;
    border-radius: 5px;
    background-color: #f5f5f5;
    .li {
      height: 30px;
      font-size: 15px;
      line-height: 30px;
      align-items: center;
      padding-left: 5px;
      border-bottom: 1px solid #000;
      margin-bottom: 2px;
    }
  }
}
</style>